<template>
  <div style="background-color: #f0f2f5; padding: 0px;">
    <PageHeader
        :breadcrumb="breadcrumb"
        style="background-color: white; padding: 24px; margin-bottom: 16px;"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px;">
      <div id="operationButton">
        <a-button
            v-if="canAddSubject"
            size="large"
            type="primary"
            @click="onAddButtonClick"
        >
          添加
        </a-button>
        &nbsp;
        <a-button
            size="large"
            type="primary"
            @click="onRefresh"
        >
          刷新
        </a-button>
        <a-modal
            v-model:visible="addOrEditDialogVisible"
            :title="addOrEditDialogTitle"
            :width="800"
            :keyboard="false"
            :maskClosable="false"
            :footer="null"
            :destroyOnClose="true"
            centered
        >
          <AddorEditSubject
              :url="editUrl"
              @operate-success="onAddOrEditSuccess"
              @operate-failed="closeAddOrEditDialog"
          />
        </a-modal>
      </div>
      <a-table
          :loading="loading"
          :columns="columns"
          :data-source="data"
          :pagination="{ pageSize: 10 }"
          :scroll="{ x: 240 }"
      >
        <template
            v-if="canEditSubject || canDeleteSubject"
            #operation="{ record }"
        >
          <TableOperation
              :canEdit="canEditSubject"
              :canDelete="canDeleteSubject"
              @edit="onEdit(record.key)"
              @delete="onDelete(record.key)"
          />
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input
                :ref="c => (searchInput = c)"
                :placeholder="`查询 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template>
                <SearchOutlined/>
              </template>
              查询
            </a-button>
            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <template #filterIcon="filtered">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>
        <template #customRender="{ text, column }">
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                    v-for="(fragment, i) in text
                    .toString()
                    .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                >
                  <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                  >
                    {{ fragment }}
                  </mark>
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>

import PageHeader from '../Common/PageHeader'
import AddorEditSubject from './AddorEditSubject'
import TableOperation from '../Common/TableOperation'
import {message} from 'ant-design-vue'
import {SearchOutlined} from '@ant-design/icons-vue'

const operationColumn = {
  title: '操作',
  dataIndex: 'operation',
  slots: {customRender: 'operation'},
  width: 150,
}

export default {
  name: 'SubjectInfo',
  emits: ['add'],
  components: {
    PageHeader,
    AddorEditSubject,
    TableOperation,
    SearchOutlined,
  },
  data() {
    const refreshInterval = 100
    return {
      breadcrumb: [
        {key: 1, title: '课题管理'},
        {key: 2, title: '课题'},
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: '',
      editUrl: '',
      canAddSubject: false,
      canEditSubject: false,
      canDeleteSubject: false,
      columns: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      refreshInterval,
    }
  },
  mounted() {
    this.columns = this.getDataColumns()
    this.processPermission()
    this.fetch()
  },
  methods: {
    getDataColumns() {
      return [
        {
          title: '课题名称',
          dataIndex: 'subject_name',
          align: 'center',
          key: 'subject_name',
          slots: {
            filterIcon: 'filterIcon',
            filterDropdown: 'filterDropdown',
            customRender: 'customRender',
          },

          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '课题类型',
          dataIndex: 'subject_type',
          align: 'center',
          key: 'subject_type',
          slots: {
            filterIcon: 'filterIcon',
            filterDropdown: 'filterDropdown',
            customRender: 'customRender',
          },

          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '关键字',
          dataIndex: 'subject_keyword',
          align: 'center',
          key: 'subject_keyword',
          slots: {
            filterIcon: 'filterIcon',
            filterDropdown: 'filterDropdown',
            customRender: 'customRender',
          },

          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '负责人',
          dataIndex: 'subject_principal',
          align: 'center',
          key: 'subject_principal',
          slots: {
            filterIcon: 'filterIcon',
            filterDropdown: 'filterDropdown',
            customRender: 'customRender',
          },

          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '参与人',
          dataIndex: 'subject_participant',
          align: 'center',
          key: 'subject_participant',
          slots: {
            filterIcon: 'filterIcon',
            filterDropdown: 'filterDropdown',
            customRender: 'customRender',
          },

          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        // {
        //   title: '审核人',
        //   dataIndex: 'subject_reviewer',
        //   align: 'center',
        // },
      ]
    },
    // 处理权限
    processPermission() {
      this.axios
          .get(
              '/has_permission?permission=subject_management.add_subject'
          )
          .then((res) => {
            this.canAddSubject = res.data.result
          })
          .catch((error) => {
            console.log('Error', error.message)
          })
      this.axios
          .get(
              '/has_permission?permission=subject_management.change_subject'
          )
          .then((res) => {
            this.canEditSubject = res.data.result
            let last = this.columns.length
            if (
                this.columns[last - 1].dataIndex !== 'operation' &&
                this.canEditSubject
            ) {
              this.columns.push(operationColumn)
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
          })
      this.axios
          .get(
              '/has_permission?permission=subject_management.delete_subject'
          )
          .then((res) => {
            this.canDeleteSubject = res.data.result
            let last = this.columns.length
            if (
                this.columns[last - 1].dataIndex !== 'operation' &&
                this.canDeleteSubject
            ) {
              this.columns.push(operationColumn)
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
          })
    },
    // 从后端获取数据
    fetch() {
      this.loading = true
      let updatedData = []
      this.axios
          .get('/subject_management/subjects/')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              const readable_subject_principal = data[i].readable_subject_principal
              let subject_principal = ''
              for (let j = 0; j < readable_subject_principal.length; ++j) {
                subject_principal += readable_subject_principal[j]
              }
              const readable_subject_participant = data[i].readable_subject_participant
              let subject_participant = ''
              for (let j = 0; j < readable_subject_participant.length; ++j) {
                if (j==0){
                subject_participant += readable_subject_participant[j]+'    '
                }else{
                subject_participant += '  ，'+readable_subject_participant[j]+'    '
                }
              }
              // let subject_reviewer = subject_participant
              updatedData.push({
                key: data[i].url,
                subject_name: data[i].subject_name,
                subject_type: data[i].subject_type,
                subject_keyword: data[i].subject_keyword,
                subject_principal: subject_principal,
                subject_participant: subject_participant,
                // subject_reviewer: subject_reviewer,
                // subject_reviewer: data[i].readable_subject_reviewer,
              })
            }
            setTimeout(() => {
              this.data = updatedData
              this.loading = false
            }, this.refreshInterval)
            // this.loading = false
            // console.log('chemical:', res)
          })
          .catch((error) => {
            setTimeout(() => {
              this.loading = false
            }, this.refreshInterval)
            console.log('Error', error.message)
          })
      this.loading = false
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = '添加课题'
      this.editUrl = ''
      this.addOrEditDialogVisible = true
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog()
      this.fetch()
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false
      this.fetch()
    },
    onEdit(key) {
      this.addOrEditDialogTitle = '编辑课题'
      // console.log(key)
      this.editUrl = key
      this.addOrEditDialogVisible = true
    },
    onDelete(key) {
      // console.log('hello', key)
      message.loading({content: '删除中...', key})
      const data = [...this.data]
      this.axios
          .delete(key)
          .then(() => {
            setTimeout(() => {
              message.success({content: '删除成功！', key, duration: 2})
              this.data = data.filter((item) => item.key !== key)
            }, 1000)
          })
          .catch((error) => {
            setTimeout(() => {
              message.error({content: '删除失败！', key, duration: 2})
            }, 1000)
            console.log('Error', error.message)
          })
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      // console.log(selectedKeys[0]);
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      // this.$forceUpdate();
    },

    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    onRefresh() {
      this.fetch()
    },
  },
}
</script>

<style>
#operationButton {
  text-align: right;
  padding: 20px;
}
</style>
